package com.z1.core.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.z1.core.PathUtil;

public class ConfigLoader {
	
	private static File configFile = null;
	private static long lastModified = 0L;
	private static Properties props = new Properties();

	private static void reload() {
		configFile = new File(PathUtil.getConfDir(), "config.properties");
		if (null == configFile || !configFile.exists() || !configFile.isFile()) {
			return;
		}
		if (lastModified != configFile.lastModified()) {
			InputStream input = null;
			try {
				input = new FileInputStream(configFile);
				props.clear();
				props.load(input);
				lastModified = configFile.lastModified();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				if (null != input) {
					try {
						input.close();
						input = null;
					}
					catch (Exception e) {}
				}
			}
		}
	}
	
	public static void rewrite(Map<String, String> map) {
		reload();
		Properties newProps = new Properties();
		newProps.putAll(getProps());
		newProps.putAll(map);
		
		OutputStream output = null;
		try {
			output = new FileOutputStream(configFile);
			newProps.store(output, "configLoader rewrite successed.");
		}
		catch (Throwable e) {
		}
		finally {
			if (null != output) {
				try {
					output.close();
					output = null;
				}
				catch (Exception e) {}
			}
		}
		reload();
	}
	
	public static String getProperty(String key) {
		reload();
		if (props.containsKey(key)) {
			Object obj = props.getProperty(key);
			if (null != obj) {
				return obj.toString();
			}
		}
		return null;
	}
	public static String getProperty(String key, String def) {
		reload();
		if (props.containsKey(key)) {
			Object obj = props.getProperty(key);
			if (null != obj) {
				return obj.toString();
			}
		}
		return def;
	}
	
	public static Map<String, String> getProps() {
		reload();
		Map<String, String> map = new HashMap<String, String>();
		for (Object key : props.keySet()) {
			map.put(key.toString(), props.get(key).toString());
		}
		return map;
	}
	
	public static Map<String, String> getRegexProps(String regex) {
		reload();
		Map<String, String> regexMap = new HashMap<String, String>();
		
		Map<String, String> map = getProps();
		for (String key : map.keySet()) {
			if (key.toString().matches(regex)) {
				regexMap.put(key.toString(), map.get(key));
			}
		}
		
		return regexMap;
	}
	
	public static boolean containsKey(String key) {
		reload();
		return props.containsKey(key);
	}
	
	public static File getConfigFile() {
		reload();
		return configFile;
	}
	
}
